import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Popconfirm,
  Input,
  Form,
  Checkbox,
  Radio,
  Space,
  InputNumber,
} from "antd";
import { connect } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import { PlusOutlined } from "@ant-design/icons";

const Page = (props) => {
  const { dispatch, submitLoading, venueArr } = props;
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef();
  const [titleType, setTitleType] = useState(0);

  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
    });
  }, []);

  const editInfo = (params) => {
    setTitleType(1);
    form.setFieldsValue({ ...params });
    setOpen(true);
    // dispatch({
    //   type: `${namespace}/queryItemInfo`,
    //   params,
    //   callback: (res) => {
    //     form.setFieldsValue({...res})
    //     setOpen(true)
    //   }
    // })
  };

  const deleteItem = ({ id }) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params: { couponId: id },
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };
  const toggleState = () => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: (res) => {
        form.setFieldsValue({ ...res });
        setOpen(true);
      },
    });
  };

  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    render: (_, record) => {
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          <Popconfirm title="确定要删除" onConfirm={() => deleteItem(record)}>
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      );
    },
  };

  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      dispatch({
        type: `${namespace}/submitItem`,
        params: {
          ...res,
          useScope: Array.isArray(res.useScope)
            ? res.useScope.join(",")
            : res.useScope,
          venueId: Array.isArray(res.venueId)
            ? res.venueId.join(",")
            : res.venueId,
        },
        callback: (res) => {
          setOpen(false);
          actionRef.current?.reload();
        },
      });
    }
    console.log(res);
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setTitleType(0);
              form.resetFields();
              setOpen(true);
            }}
          >
            新增
          </Button>,
        ]}
        scroll={{ x: 1500 }}
        pagination={{
          showSizeChanger: true,
        }}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        columns={calcColumns({ operate, venueArr })}
      />

      <Modal
        open={open}
        title={titleType ? "编辑优惠券" : "添加优惠券"}
        forceRender
        width="60%"
        onCancel={() => setOpen(!open)}
        footer={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button onClick={submitForm} loading={submitLoading} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="优惠券类型"
            name="couponType"
            rules={[{ required: true, message: "请选择优惠卷类型" }]}
          >
            <Radio.Group>
              <Radio value={"1"}>满减劵</Radio>
              <Radio value={"2"}>抵用券</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="优惠面值"
            name="couponParValue"
            rules={[{ required: true, message: "请输入优惠面值" }]}
          >
            <InputNumber
              style={{ width: "100%" }}
              // maxLength={20}
              min={0}
              defaultValue={0}
              placeholder="请输入优惠面值"
              prefix="¥"
            />
          </Form.Item>

          <Form.Item shouldUpdate noStyle>
            {() => {
              return (
                form.getFieldValue("couponType") == 2 && (
                  <Form.Item
                    label="需满金额"
                    name="needFullAmount"
                    rules={[{ required: true, message: "请输入需满金额" }]}
                  >
                    <InputNumber
                      min={0}
                      defaultValue={0}
                      prefix="¥"
                      placeholder="请输入"
                    />
                  </Form.Item>
                )
              );
            }}
          </Form.Item>

          <Form.Item
            label="可用场馆"
            name="venueId"
            rules={[{ required: true, message: "请选择可用场馆" }]}
          >
            <Checkbox.Group>
              {venueArr.map((v) => (
                <Checkbox value={v.id}>{v.venueName}</Checkbox>
              ))}
            </Checkbox.Group>
          </Form.Item>

          <Form.Item
            label="有效期(天)"
            name="effectiveDays"
            rules={[{ required: true, message: "请输入有效期" }]}
          >
            <InputNumber min={0} defaultValue={0} placeholder="请输入" />
          </Form.Item>

          <Form.Item
            label="使用范围"
            name="useScope"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Checkbox.Group>
              <Checkbox value="1">私教课</Checkbox>
              <Checkbox value="2">团课</Checkbox>
              <Checkbox value="3">班课</Checkbox>
              <Checkbox value="4">会员卡</Checkbox>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
